package filesync;

import java.io.File;

public class FileUtil {
    // Modified from http://www.adarshr.com/papers/wildcard
    /**
     * Performs a wildcard matching for the text and pattern 
     * provided.
     * 
     * @param text the text to be tested for matches.
     * 
     * @param pattern the pattern to be matched for.
     * This can contain the wildcard character '*' (asterisk).
     * 
     * @return <tt>true</tt> if a match is found, <tt>false</tt> 
     * otherwise.
     */
    public static boolean wildcardMatch(String text, String pattern) {
        // Create the cards by splitting using a RegEx. If more speed 
        // is desired, a simpler character based splitting can be done.
        String [] cards = pattern.split("\\*");
        for (String card : cards) {
            int idx = text.indexOf(card);            
            if(idx == -1) // Card not detected in the text.
                return false;           
            text = text.substring(idx + card.length()); // Move ahead, towards the right of the text.
        }        
        return true;
    }

    static public boolean matches(String s, String[] patterns) {
        boolean matched = false;

        if (patterns == null)
            return true;

        for (String pattern: patterns) {
            if (wildcardMatch(s, pattern)) {
                matched = true;
                break;
            }
        }
        return matched;
    }
    
    static public boolean same(File f1, File f2) {
        if (f1.length() != f2.length())
            return false;
        if (f1.lastModified() != f2.lastModified())
            return false;
        return true;
    }
}
